import { useState, useRef } from "react";
import { Tooltip } from "antd";
import { upload } from "@/utils/upload";

interface UploadAvatarProps {
  autoUpload?: boolean; // 是否自动上传
  onChange: (avatar?: string | File) => void;
}

export function UploadAvatar(props: UploadAvatarProps) {
  const { autoUpload = false, onChange } = props;

  const [avatar, setAvatar] = useState<string | undefined>();
  const fileInput = useRef<HTMLInputElement>(null);

  const handleAvatarChange = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    if (event.target.files && event.target.files.length > 0) {
      const file = event.target.files[0];
      if (file) {
        if (autoUpload) {
          const [success, data] = await upload(file);
          if (success) {
            onChange(data.url);
            setAvatar(data.url);
          }
        } else {
          onChange(file);
          const url = URL.createObjectURL(file);
          setAvatar(url);
        }
      }
    }
  };

  return (
    <div className="flex flex-col items-center text-white">
      <Tooltip title="上传群聊头像">
        <div className="w-14 h-14 mb-4 cursor-pointer box-border  hover:border-dashed rounded-full border-slate-400 hover:bg-slate-200 bg-slate-100">
          {avatar ? (
            <img
              src={avatar}
              alt="Avatar Preview"
              className="w-full h-full rounded-full object-cover"
            />
          ) : (
            <div
              className="w-full h-full rounded-full cursor-pointer border-2 border-dashed flex items-center justify-center text-sm text-gray-400"
              onClick={() => fileInput?.current?.click()}
            >
              <span className="iconfont icon-tianjia"></span>
            </div>
          )}

          <input
            ref={fileInput}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={handleAvatarChange}
            hidden
          />
        </div>
      </Tooltip>
    </div>
  );
}
